package com.itboye.sunsun.luntan.news;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.KeyEvent;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.homesensen.alert.ByAlert;
import com.itboye.sunsun.adapter.MySpinnerAdapter;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.TieZiCaoGaoBean;
import com.itboye.sunsun.beans.LuntanForumBean.LuntanForumItemBean;
import com.itboye.sunsun.constants.NetPublicConstant;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.custome.FaceInputView;
import com.itboye.sunsun.custome.FaceInputView.Face;
import com.itboye.sunsun.custome.FaceInputView.OnFaceClickListener;
import com.itboye.sunsun.db.DBHelper;
import com.itboye.sunsun.db.DBManager;
import com.itboye.sunsun.luntan.FaBiaoTieZiActivity;
import com.itboye.sunsun.luntan.LunTanDetailActivity;
import com.itboye.sunsun.luntan.news.RichTextEditor.EditData;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.PhotoSelectFragment;
import com.itboye.sunsun.utils.PhotoSelectFragment.PhotoSelectListener;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.utils.Spanned2String;
import com.itboye.sunsun.utils.UIAlertView;
import com.itboye.sunsun.volley.ImageCompressAndUpload;
import com.itboye.sunsun.volley.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.String2Spanned;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsunhome.R;
import com.itboye.sunsunhome.www.aq.base.MyApplication;
import com.umeng.socialize.utils.Log;

@SuppressLint("SimpleDateFormat")
public class RichTextActivity extends BaseActivity implements OnClickListener {
    private final int REQUEST_CODE_CAPTURE_CAMEIA = 100;
    private final int REQUEST_CODE_PICK_IMAGE = 200;
    private final String TAG = "RichTextActivity";
    private Context context;
    private LinearLayout line_rootView, line_addImg;
    private InterceptLinearLayout line_intercept;
    private RichTextEditor richText;
    private EditText et_name;
    private TextView tv_title, tv_ok;
    private boolean isKeyBoardUp, isEditTouch;// 判断软键盘的显示与隐藏
    private File mCameraImageFile;// 照相机拍照得到的图片
    private FileUtils mFileUtils;
    private String ROLE = "add";// 当前页面是新增还是查看详情 add/modify
    private ImageView tv_back;
    StringBuffer allContent = new StringBuffer();
    ViewGroup faceInputContainerchainse;
    Spinner tvbanvkuai;
    StringBuffer imgIds = new StringBuffer();
    ArrayList<LuntanForumItemBean> luntanForumArray = new ArrayList<>();
    private List<String> uploadedUrl = new ArrayList<String>();
    protected int position;
    DBManager dbManager;
    UIAlertView uiAlertView;
    int index;// 设置到ViewPager指定位置
    private PhotoSelectListener listener = new PhotoSelectListener() {

        @Override
        public void onPhotoSelectFinish(final List<String> paths) {
            // TODO Auto-generated method stub
            if (paths != null) {
                if (paths.size() > 0) {
                    showProgressDialog("图片上传中", true);
                    for (int i = 0; i < paths.size(); i++) {
                        position = i;
                        richText.insertImage(paths.get(i));
                        ImageCompressAndUpload.getInstance().execute(
                                paths.get(i), new OnUploadlistener() {

                                    @Override
                                    public void OnSuccess(String resultData) {
                                        uploadedUrl.add(resultData);

                                        // DebugLog.v("bytag", resultData);
                                        if (position == paths.size() - 1) {
                                            try {
                                                closeProgressDialog();
                                            } catch (Exception e) {
                                                // TODO: handle exception
                                            }
                                            Toast.makeText(App.ctx, "图片上传成功", 0)
                                                    .show();
                                            // sendToServer();
                                        }
                                    }

                                    @Override
                                    public void OnError(String resultData) {
                                        // ByAlert.alert(resultData + "error");
                                        try {
                                            closeProgressDialog();

                                        } catch (Exception e) {
                                            // TODO: handle exception
                                        }
                                    }
                                });

                    }
                }
            }
        }
    };
    private StringBuffer stringbufferContent;
    private String[] ontent;
    private boolean footHas = false;
    private StringBuffer stringBufferNew;
    String contentCopy;

    @Override
    protected void onCreate(Bundle arg0) {

        super.onCreate(arg0);

        setContentView(R.layout.richtext);
        setStatusBarColor(R.color.home_blue);
        context = this;

        richText.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub
                if (hasFocus) {
                    //的到焦点
                    System.out.println("KKKLLDKELEKLELKEKKL");
                    tv_ok.setClickable(false);
                } else {
                    //失去焦点
                    System.out.println("KKKLLDKELEwwwwwwwwwwwwwerewrwetwetweKLELKEKKL");
                    tv_ok.setClickable(true);
                }
            }
        });
        init();
    }

    String uid;

    @SuppressWarnings("unchecked")
    private void init() {
        mFileUtils = new FileUtils(context);
        dbManager = new DBManager(this);

        uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
        ArrayList<TieZiCaoGaoBean> arrayList = dbManager.queryNote(uid);
        imgIds = new StringBuffer();
        if (arrayList != null) {
            if (arrayList.size() > 0) {
                et_name.setText(arrayList.get(0).getTitle() == null ? ""
                        : arrayList.get(0).getTitle());
                richText.insertText(arrayList.get(0).getContent() == null ? String2Spanned
                        .parsed("") : String2Spanned.parsed(arrayList.get(0)
                        .getContent()));
                contentCopy = arrayList.get(0).getContent();
                System.out.println(contentCopy + "??>");
                if (arrayList.get(0).getImg() != null)
                    imgIds = new StringBuffer(arrayList.get(0).getImg());
            }
        }
        luntanForumArray = (ArrayList<LuntanForumItemBean>) getIntent()
                .getSerializableExtra("list");
        fid = luntanForumArray.get(0).getFid();
        tvbanvkuai.setSelection(0);
        tvbanvkuai.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                // TODO Auto-generated method stub
                index = position;
                fid = luntanForumArray.get(position).getFid();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });
        tvbanvkuai.setAdapter(new MySpinnerAdapter(this, luntanForumArray));// //板块类目绑定
        initRichEdit();
    }

    private void initRichEdit() {
        ImageView img_addPicture, img_takePicture;
        img_addPicture = (ImageView) line_addImg
                .findViewById(R.id.img_addPicture);
        img_addPicture.setOnClickListener(this);
        img_takePicture = (ImageView) line_addImg
                .findViewById(R.id.img_takePicture);
        img_takePicture.setOnClickListener(this);

        et_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    isEditTouch = false;
                    line_addImg.setVisibility(View.VISIBLE);
                }
            }

        });
        // 表情
        findViewById(R.id.emoj).setOnClickListener(new OnClickListener() {

            private FaceInputView faceInputView;

            @Override
            public void onClick(View v) {
                v.setSelected(!v.isSelected());
                if (faceInputView == null) {
                    faceInputView = new FaceInputView(getApplicationContext());
                    faceInputContainerchainse.addView(faceInputView);
                    faceInputView.setOnClickListener(new FaceInputListenr());
                }
                if (v.isSelected()) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(
                            richText.getWindowToken(), 0);
                    faceInputView.setVisibility(View.VISIBLE);

                } else {
                    faceInputView.setVisibility(View.GONE);
                }
            }
        });
        line_rootView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        int heightDiff = line_rootView.getRootView()
                                .getHeight() - line_rootView.getHeight();
                        if (isEditTouch) {
                            if (heightDiff > 500) {// 大小超过500时，一般为显示虚拟键盘事件,此判断条件不唯一
                                isKeyBoardUp = true;
                                // line_addImg.setVisibility(View.VISIBLE);
                            } else {
                                if (isKeyBoardUp) {
                                    isKeyBoardUp = false;
                                    isEditTouch = false;
                                    // line_addImg.setVisibility(View.GONE);
                                }
                            }
                        }
                    }
                });
    }

    private void openCamera() {
        try {
            File PHOTO_DIR = new File(mFileUtils.getStorageDirectory());
            if (!PHOTO_DIR.exists())
                PHOTO_DIR.mkdirs();// 创建照片的存储目录

            mCameraImageFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
            final Intent intent = getTakePickIntent(mCameraImageFile);
            startActivityForResult(intent, REQUEST_CODE_CAPTURE_CAMEIA);
        } catch (ActivityNotFoundException e) {
        }
    }

    private Intent getTakePickIntent(File f) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        return intent;
    }

    /**
     * 用当前时间给取得的图片命名
     */
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyy_MM_dd_HH_mm_ss");
        return dateFormat.format(date) + ".jpg";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            Uri uri = data.getData();
            tv_title.setText(Html.fromHtml("<img src='" + uri + "'/>"));
            richText.insertImage(mFileUtils.getFilePathFromUri(uri));
        } else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA
                && resultCode == Activity.RESULT_OK) {
            ImageCompressAndUpload.getInstance().execute(
                    mCameraImageFile.getAbsolutePath(), new OnUploadlistener() {

                        @Override
                        public void OnSuccess(String resultData) {
                            uploadedUrl.add(resultData);

                            Toast.makeText(App.ctx, "图片上传成功", 0).show();
                        }

                        @Override
                        public void OnError(String resultData) {
                            // ByAlert.alert(resultData + "error");
                            try {
                                closeProgressDialog();

                            } catch (Exception e) {
                                // TODO: handle exception
                            }
                        }
                    });
            richText.insertImage(mCameraImageFile.getAbsolutePath());
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mFileUtils.deleteRichTextImage();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_ok:
                // String
                // ss="<img src=\"http://sunsun.itboye.com/api.php/Picture/index?id=17600\">sfds<img src=\"http://sunsun.itboye.com/api.php/Picture/index?id=17600>sdfdhtfghr<img src=\"http://sunsun.itboye.com/api.php/Picture/index?id=17600>";
                // ss.substring(ss.indexOf("<"), ss.indexOf(">")+1);
                // System.out.println("<><>"+ss.substring(ss.indexOf("<"),
                // ss.indexOf(">")+1));
                //
                // ss.substring(ss.indexOf(">")+1).substring(ss.indexOf("<"),
                // ss.indexOf(">")+1);
                if (tv_title.getText().toString() == null) {

                    ByAlert.alert("请输入标题");
                    return;
                } else if (tv_title.getText().toString().length() >= 20) {

                    ByAlert.alert("字数不能超过20个哦!");
                    return;
                }

                // 开始处理图文混排的情况
                footHas = false;// 尾部是否含有图片标签
                stringbufferContent = new StringBuffer();
                List<EditData> listData = richText.buildEditData();
                // 记录图片的数量
                for (int i = 0; i < listData.size(); i++) {
                    EditData data = listData.get(i);
                    stringbufferContent.append(data.imagePath + data.inputStr);
                }
                System.out.println(stringbufferContent + "提交的内容>>>>>>>");
                // <img
                // src="http://sunsun.itboye.com/api.php/Picture/index?id=17600">
                // "<img src=\"\\d+\">"
                String[] innerIds = imgIds.toString().split(",");
                for (int i = 0; i < innerIds.length; i++) {
                    if (stringbufferContent.toString().contains(
                            "<img src=\"" + NetPublicConstant.URL + "/Picture/index?id="
                                    + innerIds[i])) {
                        int startIndex = stringbufferContent
                                .indexOf("<img src=\"" + NetPublicConstant.URL + "/Picture/index?id="
                                        + innerIds[i]);
                        String str = "<img src=\"" + NetPublicConstant.URL + "/Picture/index?id="
                                + innerIds[i];
                        int strLength = str.length() + 2;
                        int endIndex = startIndex + strLength;
                        stringbufferContent.replace(startIndex, endIndex, "{pic"
                                + innerIds[i] + "}");
                    }
                }
                System.out.println(stringbufferContent + "我是最新的内容了");
                ontent = stringbufferContent.toString()
                        .split("<img src=\"null\"/>");
                stringBufferNew = new StringBuffer();

                if (uploadedUrl.size() > 0) {
                    for (int j = 0; j < ontent.length; j++) {
                        System.out.println("截取出来的" + ontent[j]);
                        if (j == ontent.length - 1) {
                            stringBufferNew.append(ontent[j]);
                        } else {
                            stringBufferNew.append(ontent[j] + "<br>{pic"
                                    + uploadedUrl.get(j) + "}");
                            imgIds.append(uploadedUrl.get(j) + ",");// 重新赋值进去,防止森森休闲显示森森之家已经删除的图片
                        }
                    }
                    if (footHas) {
                        stringBufferNew.append("<br>{pic"
                                + uploadedUrl.get(uploadedUrl.size() - 1) + "}");
                    }
                } else {
                    for (int j = 0; j < ontent.length; j++) {
                        if (uploadedUrl.size() <= 0) {
                            stringBufferNew.append(ontent[j]);
                        }
                    }
                }

                sendToServer();
                break;
            case R.id.tv_back:
                // finish();
                showDelDialog();
                // showDialog();
                break;

            case R.id.img_addPicture:
                // 打开系统相册
                // Intent intent = new Intent(Intent.ACTION_PICK);
                // intent.setType("image/*");// 相片类型
                // startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                new PhotoSelectFragment(listener, 6).show(
                        getSupportFragmentManager(), null);
                break;
            case R.id.img_takePicture:
                // 打开相机
                openCamera();
                break;

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // showDialog();
            boolean isEmpty = true;
            List<EditData> datas = richText.buildEditData();
            for (int i = 0; i < datas.size(); i++) {
                EditData data = datas.get(i);
                System.out.println(i + "::" + data.imagePath + "-----"
                        + data.inputStr);
                if (data.imagePath != null || !data.inputStr.equals("")) {
                    isEmpty = false;
                    break;
                } else {
                    isEmpty = true;
                }
            }
            if (!et_name.getText().toString().trim().equals("")
                    || isEmpty == false) {
                showDelDialog();
            } else {
                finish();
            }
            return false;
        }
        return true;
    }

    private void showDelDialog() {
        final String uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
        uiAlertView = new UIAlertView(this, "温馨提示！", "是否保存？", "取消", "保存");
        uiAlertView.show();

        uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {

            public void doLeft() {
                uiAlertView.dismiss();
                dbManager.deleteRi(uid);
                finish();
            }

            public void doRight() {
                String save_title = et_name.getText().toString().trim();

                String title;

                stringbufferContent = new StringBuffer();
                List<EditData> listData = richText.buildEditData();
                // 记录图片的数量
                for (int i = 0; i < listData.size(); i++) {
                    EditData data = listData.get(i);
                    stringbufferContent.append(data.imagePath + data.inputStr);
                }
                title = stringbufferContent.toString();
                String[] innerIds = imgIds.toString().split(",");
                for (int i = 0; i < innerIds.length; i++) {
                    if (stringbufferContent.toString().contains(
                            "<img src=" + NetPublicConstant.IMAGE_URL + innerIds[i])) {
                        int startIndex = stringbufferContent
                                .indexOf("<img src=" + NetPublicConstant.IMAGE_URL
                                        + innerIds[i]);
                        String str = "<img src=" + NetPublicConstant.IMAGE_URL
                                + innerIds[i];
                        int strLength = str.length() + 2;
                        int endIndex = startIndex + strLength;
                        stringbufferContent.replace(startIndex, endIndex,
                                "{pic" + innerIds[i] + "}");
                    }
                }
                System.out.println(stringbufferContent + "提交的内容>>>>>>>");
                ontent = stringbufferContent.toString().split(
                        "<img src=\"null\"/>");
                for (int i = 0; i < uploadedUrl.size(); i++) {
                    if (stringbufferContent.toString().contains(
                            "<img src=\"null\"/>")) {
                        int startIndex = stringbufferContent
                                .indexOf("<img src=\"null\"/>");
                        int endIndex = startIndex + 17;
                        stringbufferContent.replace(startIndex, endIndex,
                                "{pic" + uploadedUrl.get(i) + "}");
                    }
                    imgIds.append(uploadedUrl.get(i) + ",");
                }

                // stringBufferNew = new StringBuffer();
                //
                //
                // imgIds = new StringBuffer();
                // if (uploadedUrl.size() > 0) {
                // for (int j = 0; j < ontent.length; j++) {
                // System.out.println("截取出来的" + ontent[j]);
                // if (j == ontent.length - 1) {
                // stringBufferNew.append(ontent[j]);
                // } else {
                // stringBufferNew.append(ontent[j] + "<br>{pic"
                // + uploadedUrl.get(j) + "}");
                // imgIds.append(uploadedUrl.get(j) + ",");//
                // 重新赋值进去,防止森森休闲显示森森之家已经删除的图片
                // }
                // }
                // if (footHas) {
                // stringBufferNew.append("<br>{pic"
                // + uploadedUrl.get(uploadedUrl.size() - 1) + "}");
                // }
                // } else {
                // for (int j = 0; j < ontent.length; j++) {
                // if (uploadedUrl.size() <= 0) {
                // stringBufferNew.append(ontent[j]);
                // }
                // }
                // }
                //
                dbManager.deleteRi(uid);
                long result = dbManager.addRich(uid, save_title,
                        stringbufferContent.toString().replace("null", "")
                                .toString(),
                        imgIds.length() <= 0 ? "" : imgIds.toString());
                if (result <= 0) {
                    ByAlert.alert("保存到草稿失败！");
                } else {
                    ByAlert.alert("保存到草稿成功！");
                }
                finish();

            }
        });
    }

    private void showDialog() {
        // TODO Auto-generated method stub

        final AlertDialog alertDialog = new AlertDialog.Builder(
                RichTextActivity.this).create();
        alertDialog.show();
        final String uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_save);
        TextView tv_title = (TextView) window.findViewById(R.id.title);
        tv_title.setText("温馨提示");
        TextView tv_message = (TextView) window.findViewById(R.id.message);
        tv_message.setText("是否保存编辑内容");
        Button btn_save = (Button) window.findViewById(R.id.save);
        Button btn_noSave = (Button) window.findViewById(R.id.noSave);
        Button canButton = (Button) window.findViewById(R.id.cancel);
        btn_save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String save_title = et_name.getText().toString().trim();

                String title;

                stringbufferContent = new StringBuffer();
                List<EditData> listData = richText.buildEditData();
                // 记录图片的数量
                for (int i = 0; i < listData.size(); i++) {
                    EditData data = listData.get(i);
                    stringbufferContent.append(data.imagePath + data.inputStr);
                }
                title = stringbufferContent.toString();

                System.out.println(stringbufferContent + "提交的内容>>>>>>>");
                ontent = stringbufferContent.toString().split(
                        "<img src=\"null\"/>");
                stringBufferNew = new StringBuffer();
                imgIds = new StringBuffer();
                if (uploadedUrl.size() > 0) {
                    for (int j = 0; j < ontent.length; j++) {
                        System.out.println("截取出来的" + ontent[j]);
                        if (j == ontent.length - 1) {
                            stringBufferNew.append(ontent[j]);
                        } else {
                            stringBufferNew.append(ontent[j] + "{pic"
                                    + uploadedUrl.get(j) + "}");
                            imgIds.append(uploadedUrl.get(j) + ",");// 重新赋值进去,防止森森休闲显示森森之家已经删除的图片
                        }
                    }
                    if (footHas) {
                        stringBufferNew.append("{pic"
                                + uploadedUrl.get(uploadedUrl.size() - 1) + "}");
                    }
                } else {
                    for (int j = 0; j < ontent.length; j++) {
                        if (uploadedUrl.size() <= 0) {
                            stringBufferNew.append(ontent[j]);
                        }
                    }
                }

                System.out.println("contemte" + title);
                dbManager.deleteRi(uid);
                long result = dbManager.addRich(uid, save_title,
                        stringBufferNew.toString().replace("null", "")
                                .toString(),
                        imgIds.length() <= 0 ? "" : imgIds.toString());
                if (result <= 0) {
                    ByAlert.alert("保存到草稿失败！");
                } else {
                    ByAlert.alert("保存到草稿成功！");
                }
                finish();
            }
        });
        btn_noSave.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dbManager.deleteRi(uid);
                finish();
            }
        });
        canButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
            }
        });

    }

    private class FaceInputListenr implements OnFaceClickListener {

        @Override
        public void selectedFace(Face face) {
            int id = face.faceId;
            if (id == R.drawable.ic_face_delete_normal)// 删除按钮
            {
                int index = richText.getSelectionStart();
                if (index == 0)
                    return;
                Editable editable = richText.lastFocusEdit.getText();
                editable.delete(index - 1, index);// 删除最后一个字符或表情
            } else {
                richText.lastFocusEdit.append(Html.fromHtml("<img src='" + id
                        + "'/>", imageGetter, null));// 添加表情
            }
        }

    }

    // 输入表情需要
    ImageGetter imageGetter = new ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            int id = Integer.parseInt(source);
            Drawable d = getResources().getDrawable(id);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            return d;
        }
    };
    private String fid;

    private void sendToServer() {

        if (et_name.getText().toString().equals("")) {
            ByAlert.alert("标题不能为空");
            return;
        }
        // else if (richText.getText().toString().equals("")) {
        // ByAlert.alert("没有编辑内容哟！");
        // return;
        // }
        if (et_name.getText().toString().length() > 20) {
            ByAlert.alert("标题内容过长");
            return;
        }
        MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<>();
        builder.apiVer("100")
                .typeKey("BY_ForumThread_add")
                .param("fid", fid)

                .param("typeid", "0")
                .param("author",
                        (String) SPUtils.get(getApplicationContext(), null,
                                SPContants.NICK, ""))
                .param("author_id",
                        (String) SPUtils.get(getApplicationContext(), null,
                                SPContants.USER_ID, ""))
                .param("subject", et_name.getText().toString())

                .param("attachments",
                        imgIds.length() <= 0 ? "" : imgIds.substring(0,
                                imgIds.length() - 1))
                .param("message",
                        stringBufferNew.toString().replace("null", ""));

        builder.requestListener(new XRequestListener<String>() {

            @Override
            public void onResponse(String arg0) {
                // TODO Auto-generated method stub
                dbManager.deleteRi(uid);
                ByAlert.alert(arg0);
                LunTanDetailActivity.activity.setCurrentPager(index);// 设置滚动到当前发表的pager选项
                Intent intent = new Intent("refresh");// 刷新当前论坛内容
                sendBroadcast(intent);
                finish();
            }
        }).errorListener(new XErrorListener() {

            @Override
            public void onErrorResponse(Exception exception, int code,
                                        String msg) {
                // TODO Auto-generated method stub
                // Toast.makeText(getApplicationContext(), msg, 1).show();
                if (msg.equals("发贴间隔2分钟，请先休息一下~")) {
                    ByAlert.alert(msg);
                } else
                    Log.v("errorcode", "haha" + code);
                Log.v("errormsg", "haha" + msg);
            }
        });
        HttpRequest.getDefaultRequestQueue().add(builder.build());

    }

}
